#!/usr/bin/env python
# encoding: utf-8
"""
snap_compare.py

Created by Bud Gibson on 2010-07-01.
Copyright (c) 2010 Bud Gibson. Available under the GPL/Artistic License.
"""

import config
import buzztracker.persistnet.snapshots as snap
from buzztracker.analytics.group_compare import group_difference
from buzztracker.utilities.sorters import sort_displayName
from buzztracker.utilities import dj

def snap_compare(index_ref_snap=0,index_compared_snap=-1,collection=snap):
  """Compare one network snapshot to a prior reference snapshot"""
  reference = collection.get_snap(index_ref_snap)
  compared = collection.get_snap(index_compared_snap)
  pairs = zip(compared['participants'],reference['participants'])
  for pair in pairs:
    for el in ['mutual', 'unreciprocated', 'otherFollowers']:
      pair[0][el + '_gains'] = group_difference(pair[0][el],
        pair[1][el])
      pair[0][el + '_gains'].sort(sort_displayName)
      pair[0][el + '_losses'] = group_difference(pair[1][el],
        pair[0][el])
      pair[0][el + '_losses'].sort(sort_displayName)
      for suff in ['_gains', '_losses']:
        pair[0][el + suff + '_count'] = len(pair[0][el + suff])
  compared['participants'], t = zip(*pairs)
  compared['referenceDate'] = reference['dateRun']
  return compared
  
def display_snap_compare(
  struct,
  out_file_stem='./output/mutualTracking-',
  template_file=None
  ):
  """Outputs a snapshot from the database in html format"""
  out_file = ''.join([
    out_file_stem, #base name
    str(struct['dateRun']).replace(' ','-').replace(':','.'), #unique ID
    '.html' #extension
    ])
  dj.run(struct,out_file,template_file)


def main():
  import pprint
  pp = pprint.PrettyPrinter(depth=3)
  compared = snap_compare()
  display_snap_compare(compared,template_file='mutualTrackingTemplate.html')


if __name__ == '__main__':
  main()

